
'use client'

import { Button, Calendar, CalendarMode, CalendarProps, Descriptions, Dropdown, Modal, Select, Space } from "antd";
import { HolidayUtil, Lunar, Solar } from "lunar-typescript";
import style from './index.module.css'
import classNames from 'classnames'
import { useEffect, useState } from "react";
import dayjs, { Dayjs } from "dayjs";
import dayOfYear from 'dayjs/plugin/dayOfYear';
import 'dayjs/locale/zh-cn';
import dayLocaleData from 'dayjs/plugin/localeData';
import { DoubleLeftOutlined, DownOutlined, LeftOutlined, RightOutlined } from "@ant-design/icons";
type FieldType = {
    description?: string;
};
dayjs.locale('zh-cn');
dayjs.extend(dayOfYear);
dayjs.extend(dayLocaleData);
const EditNoteView: React.FC<{ handleCancle: () => void; }> = ({ handleCancle }) => {
    const [selectDate, setSelectDate] = useState<Dayjs>(dayjs());
    const [panelDateDate, setPanelDate] = useState<Dayjs>(dayjs());
    const [selectedDateInfo, setSelectedDateInfo] = useState<any>(null);
    useEffect(() => {
        const dateInfo = getDateInfo(selectDate);
        setSelectedDateInfo(dateInfo);
    }, [selectDate]);
    /**
    * 获取日期详细信息
    */
    const getDateInfo = (date: Dayjs) => {
        // 将 Dayjs 日期转换为 Lunar 对象
        const lunar = Lunar.fromDate(date.toDate());   //农历对象
        const solar = Solar.fromDate(date.toDate());   //公历对象
        // 基本信息
        const solarDate = date.format('YYYY年MM月DD日');                    // 公历日期格式化
        const lunarDate = lunar.toString();                                 // 农历日期字符串
        const ganZhiYear = lunar.getYearInGanZhi();                         // 干支纪年
        const ganZhiMonth = lunar.getMonthInGanZhi();                       // 干支纪月
        const ganZhiDay = lunar.getDayInGanZhi();                           // 干支纪日
        const chineseZodiac = lunar.getYearShengXiao();                     // 生肖

        const constellation = solar.getXingZuo();                       // 星座

        // 节气信息处理
        const solarTerm = lunar.getJieQi();                                 // 当前节气对象
        const solarTermName = solarTerm ? solarTerm.toString() : '无';      // 节气名称或"无"

        const nextSolarTerm = lunar.getNextJieQi();                         // 下一个节气对象
        let nextSolarTermName = '无';                                       // 下一个节气名称
        let nextSolarTermDays = null;                                       // 距离下一个节气的天数

        // 如果有下一个节气，计算相关信息
        if (nextSolarTerm) {
            nextSolarTermName = nextSolarTerm.getName();                    // 获取节气名称
            const nextSolarTermDate = nextSolarTerm.getSolar();             // 获取节气日期对象
            nextSolarTermDays = Math.abs(dayjs(nextSolarTermDate.toYmd()).diff(date, 'day')); // 计算天数差
        }

        // 节日信息
        const h = HolidayUtil.getHoliday(date.get('year'), date.get('month') + 1, date.get('date')); // 节日
        // const holiday = h?.getName();                                       // 农历节日名称
        const lunarHoliday = lunar.getFestivals().concat(lunar.getOtherFestivals());                                       // 农历节日名称

        // 阴历节日信息
        const solarHoliday = solar.getFestivals().concat(solar.getOtherFestivals());
        console.log("lunarHoliday", solarHoliday);                   // 公历节日

        // 日期统计信息
        const week = ['日', '一', '二', '三', '四', '五', '六'][date.day()]; // 星期几
        const dayOfYearValue = date.dayOfYear();                            // 一年中的第几天
        const daysLeftInYear = date.endOf('year').diff(date, 'day');        // 年内剩余天数

        // 返回所有日期信息
        return {
            solarDate,
            lunarDate,
            ganZhiYear,
            ganZhiMonth,
            ganZhiDay,
            chineseZodiac,
            constellation,
            solarTerm: solarTermName,
            nextSolarTerm: nextSolarTermName,
            nextSolarTermDays,
            lunarHoliday: lunarHoliday || '无',
            solarHoliday: solarHoliday.length > 0 ? solarHoliday.join(', ') : '无',
            week: `星期${week}`,
            dayOfYear: dayOfYearValue,
            daysLeftInYear,
            isWork: h?.isWork()
        };
    };



    /**
      * 
      * @param newValue 选择日期
      * @param selectInfo 
      */
    const onSelect: CalendarProps<Dayjs>['onSelect'] = (newValue: Dayjs, selectInfo) => {
        if (selectInfo.source === 'date') {
            setSelectDate(newValue);
        }
    };
    /**
  * 
  * @param newValue 面板改变
  */
    const onPanelChange = (newValue: Dayjs) => {
        setPanelDate(newValue);
    };
    /**
 * 处理日期单元格点击
 */
    const handleDateClick = (date: Dayjs, event: React.MouseEvent) => {
        event.stopPropagation(); // 阻止事件冒泡
        console.log('点击的日期:', date.format('YYYY-MM-DD'));

        // const dateInfo = getDateInfo(date);
        // setSelectedDateInfo(dateInfo);
        setSelectDate(date);
        // 这里可以添加你的自定义逻辑
        // 例如打开弹窗、显示详情等
    };

    /**
     * 处理月份单元格点击
     */
    const handleMonthClick = (date: Dayjs, event: React.MouseEvent) => {
        event.stopPropagation();
        console.log('点击的月份:', date.format('YYYY-MM'));
        setPanelDate(date);

        // 月份点击的逻辑
    };
    /**
     * 
     * @param current 重新定义面板
     * @param info 
     * @returns 
     */
    const cellRender: CalendarProps<Dayjs>['cellRender'] = (current, info) => {
        const d = Lunar.fromDate(current.toDate());
        const lunar = d.getDayInChinese();//初几
        const solarTerm = d.getJieQi();//节气

        const h = HolidayUtil.getHoliday(current.get('year'), current.get('month') + 1, current.get('date'));
        const isWork = h?.isWork() === true ? "班" : h?.isWork() === false ? "休" : null;//是否调休
        const displayHoliday = h?.getTarget() === h?.getDay() ? h?.getName() : undefined;//节日
        if (info.type == "date") {
            return (<div onClick={(e) => handleDateClick(current, e)} className={classNames(style.SelectDataClass, { [style.SelectDataColorClass]: selectDate.isSame(current, 'date') })}>
                {/* 公历 */}
                <div className={style.DateClass}>{current.get("date")}</div>
                {/* 农历 */}
                <div className={style.lunarClass}> {displayHoliday || solarTerm || lunar}</div>
                {/* 是否调休和假日休息 */}
                <div className={style.isWorkClass}> {isWork}</div>
            </div>);
        }
        if (info.type == 'month') {
            const d2 = Lunar.fromDate(new Date(current.get('year'), current.get('month')));
            const month = d2.getMonthInChinese();


            return (<div onClick={(e) => handleMonthClick(current, e)}
                className={classNames(style.SelectDataClass, { [style.SelectDataColorClass]: panelDateDate.isSame(current, 'month') })}  >
                <div className={style.MounthClass}>  {current.get('month') + 1}月（{month}月）</div>
            </div>)
        }
    }
    const customHeaderRender = (value: any, type: CalendarMode, onChange: any, onTypeChange: any) => {
        const year = value.year();
        const month = value.month();

        const yearOptions = Array.from({ length: 20 }, (_, i) => {
            const label = year - 10 + i;
            return { label, value: label };
        });

        const monthOptions = value
            .localeData()
            .monthsShort()
            .map((label: any, index: any) => ({
                label,
                value: index,
            }));

        // 处理年份变化
        const handleYearChange = (newYear: number) => {
            const now = value.clone().year(newYear);
            onChange(now);
        };

        // 处理月份变化
        const handleMonthChange = (newMonth: number) => {
            const now = value.clone().month(newMonth);
            onChange(now);
        };

        // 处理导航按钮点击
        const handlePrevMonth = () => {
            const now = value.clone().subtract(1, 'month');
            onChange(now);
        };

        const handleNextMonth = () => {
            const now = value.clone().add(1, 'month');
            onChange(now);
        };
        // 回到今天
        const handleBackToToday = () => {
            const today = dayjs();
            onChange(today);
            setSelectDate(today); // 同时更新选中的日期
        };
        return (
            <div className="flex justify-between items-center p-2 bg-[#808080] text-amber-50 select-none">
                <div className="flex items-center select-none p-1.5  rounded-full" onClick={handleCancle}><DoubleLeftOutlined /></div>
                <div className="flex flex-1 justify-end items-center pr-5">
                    {/* 年份选择器 */}
                    <Select
                        className={style.transparentSelect}
                        size="small"
                        popupMatchSelectWidth={false}
                        value={year}
                        options={yearOptions}
                        onChange={handleYearChange}
                    />

                    {/* 月份选择器 */}
                    <Select
                        className={style.transparentSelect}
                        size="small"
                        popupMatchSelectWidth={false}
                        value={month}
                        options={monthOptions}
                        onChange={handleMonthChange}
                    />

                </div>
                <div className="px-2 py-1 text-xs  border-opacity-30 rounded hover:bg-gray-600 transition-colors" onClick={handleBackToToday}>今天</div>

                {/* 月份导航按钮 */}
                <div className="flex cursor-pointer border rounded p-0.5 select-none shrink-0">
                    <div
                        className="min-w-8 text-center border-r hover:bg-gray-600"
                        onClick={handlePrevMonth}
                    >
                        <LeftOutlined />
                    </div>
                    <div
                        className="min-w-8 text-center hover:bg-gray-600"
                        onClick={handleNextMonth}
                    >
                        <RightOutlined />
                    </div>
                </div>
            </div>
        );
    };
    return (
        <div className=" p-5 h-screen bg-[#808080]">
            <div className="h-3/5  text-amber-50">
                <Calendar headerRender={({ value, type, onChange, onTypeChange }) => {

                    return customHeaderRender(value, type, onChange, onTypeChange);
                }} className={style.transparentCalendar} defaultValue={selectDate} fullscreen={false} fullCellRender={cellRender} onSelect={onSelect} onPanelChange={onPanelChange} />
            </div>
            <div className="h-2/5 pt-20">
                {/* 日期信息详情展示 */}
                {selectedDateInfo && (
                    <div>
                        <Descriptions className=" overflow-y-auto max-h-70" column={{ xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }} bordered size="small">
                            <Descriptions.Item label="公历日期">{selectedDateInfo.solarDate}</Descriptions.Item>
                            <Descriptions.Item label="农历日期">{selectedDateInfo.lunarDate}</Descriptions.Item>
                            <Descriptions.Item label="干支纪年">{selectedDateInfo.ganZhiYear}</Descriptions.Item>
                            <Descriptions.Item label="干支纪月">{selectedDateInfo.ganZhiMonth}</Descriptions.Item>
                            <Descriptions.Item label="干支纪日">{selectedDateInfo.ganZhiDay}</Descriptions.Item>
                            <Descriptions.Item label="生肖">{selectedDateInfo.chineseZodiac}</Descriptions.Item>
                            <Descriptions.Item label="星座">{selectedDateInfo.constellation}</Descriptions.Item>
                            <Descriptions.Item label="星期">{selectedDateInfo.week}</Descriptions.Item>
                            <Descriptions.Item label="当前节气">{selectedDateInfo.solarTerm}</Descriptions.Item>
                            <Descriptions.Item label="下一个节气">
                                {selectedDateInfo.nextSolarTerm}
                                {selectedDateInfo.nextSolarTermDays && ` (还有${selectedDateInfo.nextSolarTermDays}天)`}
                            </Descriptions.Item>
                            <Descriptions.Item label="农/阴历节日">{selectedDateInfo.lunarHoliday}</Descriptions.Item>
                            <Descriptions.Item label="公/阳历节日">{selectedDateInfo.solarHoliday}</Descriptions.Item>
                            <Descriptions.Item label="调休信息">
                                {selectedDateInfo.isWork === true ? '班' :
                                    selectedDateInfo.isWork === false ? '休' : '正常'}
                            </Descriptions.Item>
                            <Descriptions.Item label="年内第几天">第 {selectedDateInfo.dayOfYear} 天</Descriptions.Item>
                            <Descriptions.Item label="年内剩余天数">还有 {selectedDateInfo.daysLeftInYear} 天</Descriptions.Item>
                        </Descriptions>
                    </div>


                )}
            </div>
        </div >
    )

}
export default EditNoteView;